import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../vuex'

// 首页
import Home from '@/pages/Home/Home'

// 登录页面
import Login from '@/pages/Login/Login'

// 用户页面
import User from '@/pages/User/UserCenter'

// 购物车页面
import Cart from '@/pages/Cart/Cart'

// 商品页面
import Product from '@/pages/Product/Product'

// 订单页面
import OrderList from '@/pages/Order/List'
import OrderDetail from '@/pages/Order/Detail'
import OrderPreview from '@/pages/Order/Preview'

// 重写push 避免新版本router报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home,
    meta: {
      name: '首页'
    }
  },
  {
    path: '/home',
    name: 'productList',
    component: Home,
    meta: {
      name: '首页'
    }
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: {
      name: '登录',
      disableToolbar: true
    }
  },
  {
    path: '/cart',
    name: 'cart',
    component: Cart,
    meta: {
      userAuth: true,
      name: '购物车',
      disableToolbar: true
    }
  },
  {
    path: '/product/detail',
    name: 'productDetail',
    component: Product,
    meta: {
      name: '商品详情',
      disableToolbar: true
    }
  },
  {
    path: '/order',
    name: 'orderList',
    component: OrderList,
    meta: {
      userAuth: true,
      name: '我的订单'
    }
  },
  {
    path: '/order/detail',
    name: 'orderDetail',
    component: OrderDetail,
    meta: {
      userAuth: true,
      name: '订单详情'
    }
  },
  {
    path: '/order/preview',
    name: 'orderPreview',
    component: OrderPreview,
    meta: {
      userAuth: true,
      name: '订单确认',
      disableToolbar: true
    }
  },
  {
    path: '/user',
    name: 'user',
    component: User,
    meta: {
      userAuth: true,
      name: '个人中心'
    }
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // 检测路由配置中route.meta.userAuth字段来确定该页面是否需要先登录
  if (to.matched.some(record => record.meta.userAuth)) {
    // 判断是否已登录
    if (store.getters.userLogged) {
      next()
      return
    }
    // 登录后重定向
    next({ name: 'login', params: { redirect: to.fullPath } })
  } else {
    next()
  }
})

export default router
